<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/7/26 14:49}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace wxpay;
use think\Db;
class Wx{
    protected $appId = 'wx2a66cde38cb7ab28'; //小程序id
    protected $appSecret = 'e20e541c71d7f73635437d3a9006df08'; //小程序秘钥

    public function getAuthLogin($code)
    {
        $result = [
            'status'    =>  false,
            'msg'       =>  '',
            'openid'    =>  '',
            'session_key'=> '',
        ];

        if (!$code)
        {
            $result['msg'] = '参数错误';
            return $result;
        }

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appId.'&secret='.$this->appSecret.'&js_code='.$code.'&grant_type=authorization_code';

        $response = json_decode(request_url($url), true);

        if (!empty($response['errcode']))
        {
            $result['msg'] = $response['errmsg'];
            return $result;
        }
        $result['status'] = true;
        $result['openid'] = $response['openid'];
        $result['session_key'] = $response['session_key'];
        return $result;
    }

    public function getAccessToken()
    {

        $authtoken = Db::name('auth_token')->where('type','wx')->find();
        $time = time();
        if (empty($authtoken) || $authtoken['updatetime'] <= $time)
        {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret='.$this->appSecret;
            $res = json_decode(request_url($url),true);
            Db::name('auth_token')->where('type','wx')->update([
                'asscesstoken' => $res['access_token'],
                'updatetime'    => $time + 7100,
            ]);
            $token = $res['access_token'];
        }else{
            $token = $authtoken['asscesstoken'];
        }

        return $token;
    }

    public function getPhoneNumber($code)
    {
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
        $data = [
            'code' => $code
        ];
        $data = json_encode($data);
        $res = json_decode(request_url($url,$data,'json'),true);

        if ($res['errmsg'] == 'ok')
        {
            return $res['phone_info']['purePhoneNumber'];
        }else{
            return false;
        }

    }

}

